'use strict';

app.controller('planTaskCtrl', ['$scope', '$http','$modal', '$stateParams', '$rootScope', '$filter', '$location', '$timeout','lodash', function ($scope, $http, $modal, $stateParams, $rootScope, $filter, $location, $timeout,lodash) {
    $scope.urlKeyword="";
    $rootScope.initBreadcrumb($scope.breadcrumb);
    //页面加载时，给headerElement设置元素
    $rootScope.initHeaderElements($scope.settings);
    $scope.settings.searchEle = {
        show: true,                   //显示查询框
        func: function(keyword) {     //点击查询框调用的方法
            $scope.urlKeyword = keyword ? keyword : "";
            getPlanTaskList();
        },
        blurFunc: function(keyword) {
            $scope.urlKeyword = keyword ? keyword : "";
        }
    };
   
    $scope.app.headerPanel.buttons = [];
    var backUrl = {
        show: true,
        label: "返回",
        func: function () {
            $rootScope.backHistory();
        }
    }
    var addTask = {
        show: true,
        label: "新增",
        func: function () {
            $scope.addTask();
        }
    }
    $scope.settings.btnEle.push(addTask);
    $scope.settings.btnEle.push(backUrl);
    //结束headerElement设置
    
    $scope.users        = []; 
    $scope.urlUser      = "";
    $scope.statusList   = [];
    $scope.urlStatus    = "";
    $scope.taskTypeList = [];
    $scope.urlTaskType  = "";
    
    $scope.info = {
        projectPlanId   : $stateParams.id,
        projectPlanInfo : {},
        taskThdata      : [
            // {"thName": "编号"},
            {"thName": "负责人"},
            {"thName": "任务类型"},
            {"thName": "内容"},
            {"thName": "状态"},
            {"thName": "工时"},
        ],
        taskPage        : {"isTrue": true},
        planTaskList    : {
            "trIsClick": false,
            "isOperation": {
                "Delete": {"isTrue": true, "msg": "取消"},
                "Complete": {"isTrue": true, "msg": "完成"},
                "Ing": {"isTrue": true, "msg": "延期"},
                "Update":{"isTrue":true,"msg":"更新"},
                "up":{"isTrue":true,"msg":"进展中"}
            },
            "tdName": [
                // {"name": "number"},
                {"name": "chargerRealname"},
                {"name": "typeName"},
                {"name": "content"},
                {"name": "statusName"},
                {"name": "workHours"}
            ]
        }
    };
    setStorage('brdBackUrl', $location.url());

    getProjectPlanDetails();
    getUserList()
    getStatusList();
    //getTaskTypeList();
    //getPlanTaskList();   //已在getStatusList中调用

    //获取项目计划详情（仅使用projectPlanName字段）
    function getProjectPlanDetails() {
        var url = matrix_product_url +"/projectPlan/getProjectPlans?containFinished=Y&projectPlanId="+ $scope.info.projectPlanId;
        $http.get(url).success(function(result) {
            if(result.code == "0") {
                $scope.info.projectPlanInfo = result.data[0];
                $scope.breadcrumb.push('项目计划',$scope.info.projectPlanInfo.projectPlanName);
            } else {
                $rootScope.toasterErrorInfo(result.msg);
            }
        });
    };

    //获取计划任务列表数据
    function getPlanTaskList() {
        var url = matrix_product_url +"/task/getTasks";
        var urlArray = [
            {"type": "projectPlanId", "param": $scope.info.projectPlanId},
            {"type": "type", "param": $scope.urlTaskType},
            {"type": "status", "param": $scope.urlStatus},
            {"type": "chargerAccount", "param": $scope.urlUser},
            {"type": "number", "param": $scope.urlKeyword}];
        url = $rootScope.setUrlParams(url, urlArray);
        $http.get(url).success(function(result) {
            if(result.code == "0") {
                angular.forEach(result.data, function(task) {
                    var statusItem = lodash.findWhere(config_taskStatus, {key: task.status});
                    task.statusName = statusItem.name;
                    angular.forEach($scope.taskTypeList, function(type) {
                        if(task.type==type.key){
                            task.typeName=type.value;
                        }
                    });
                });
                var data = result.data
                console.log(data)
                data.sort(compare("id"))
                // $scope.info.planTaskList.datas = data.reverse();
                $scope.info.planTaskList.datas = data
            } else {
                $scope.info.planTaskList.datas = [];
                $rootScope.toasterErrorInfo(result.desc);
            }
        });
    }

     //任务类型
    function getTaskTypeList() {
        var url = sys_config_url+"/select/get?type=BRD_STATUS";
        $http.get(url).success(function(result) {
            if(result.code == "0") {
                if(result.data) {
                    var taskTypeArray = [{"crtname": "全部任务类型", "id": 0}];
                    angular.forEach(taskTypes, function(data) {
                        data.crtname = data.value;
                        taskTypeArray.push(data);
                    });
                    $scope.taskTypeList = taskTypes;
                    setHeaderTaskType(taskTypeArray);
                    getPlanTaskList();
                } else {
                    $rootScope.toasterErrorInfo("获取任务类型数据错误！");
                }
            } else {
                $rootScope.toasterErrorInfo(result.desc);
            }
        });
    };

    //设置header中的任务类型
    function setHeaderTaskType(taskTypeList) {
        var fondnessTaskType = "";
        if($scope.urlTaskType) {
            var crtTaskType     = lodash.findWhere(taskTypeList, {"key": $scope.urlTaskType});
            crtTaskType.crtname = crtTaskType.key;
            fondnessTaskType    = crtTaskType;
        } else {
            fondnessTaskType = {"crtname": "全部任务类型", "key": 0};
        }
        var taskTypeSelectEle = {
            status       : true,
            items        : taskTypeList,
            prompt       : "全部任务类型",
            selectedItem : fondnessTaskType,
            func : function(item) {
                $scope.urlTaskType = item.key ? item.key : "";
                getPlanTaskList()
            }
        };
        $scope.settings.uiSltEle.push(taskTypeSelectEle);
    };
   
    //负责人
    function getUserList() {
        var url = beetle_auth_url +"/user/?token_id="+ getTokenId();
        $http.get(url).success(function(result) {
            if(result.success) {
                if(result.data) {
                    var accountArray = [{"crtname": "全部负责人", "id": 0}];
                    angular.forEach(result.data, function(data) {
                        data.crtname = data.realname;
                        accountArray.push(data);
                    });
                    $scope.users = result.data;
                    setHeaderUser(accountArray);
                } else {
                    $rootScope.toasterErrorInfo("获取负责人数据错误！");
                }
            } else {
                $rootScope.toasterErrorInfo(result.msg);
            }
        });
    };

    //设置header中的用户（负责人）
    function setHeaderUser(userList) {
        var fondnessAccount = "";
        if($scope.urlUser) {
            var crtAccount     = lodash.findWhere(userList, {"account": $scope.urlUser});
            crtAccount.crtname = crtAccount.realname;
            fondnessAccount    = crtAccount;
        } else {
            fondnessAccount = {"crtname": "全部负责人", "id": 0};
        }
        var userSelectEle = {
            status       : true,
            items        : userList,
            prompt       : "全部负责人",
            selectedItem : fondnessAccount,
            func : function(item) {
                $scope.urlUser = item.account ? item.account : "";
                getPlanTaskList()
            }
        };
        $scope.settings.uiSltEle.push(userSelectEle);
    };

    //状态
    function getStatusList() {
        $scope.statusList = config_taskStatus;

        var statusArray = [{"crtname": "全部状态", "key": 0}];
        angular.forEach(config_taskStatus, function(status) {
            status.crtname = status.name;
            statusArray.push(status);
        });
        
        setHeaderStstus(statusArray);
        getTaskTypeList();
    };

    //设置状态
    function setHeaderStstus(statusList) {
        var fondnessStatus = "";
        if($scope.urlStatus) {
            var crtStatus     = lodash.findWhere(statusList, {"key": $scope.urlStatus});
            crtStatus.crtname = crtStatus.key;
            fondnessStatus    = crtStatus;
        } else {
            fondnessStatus = {"crtname": "全部状态", "key": 0};
        }
        var statusSelectEle = {
            status       : true,
            items        : statusList,
            prompt       : "全部状态",
            selectedItem : fondnessStatus,
            func : function(item) {
                $scope.urlStatus = item.key ? item.key : "";
                getPlanTaskList()
            }
        };
        $scope.settings.uiSltEle.push(statusSelectEle);
    };

    //取消
    $scope.cancelStatus=function(info){
        var confirmParams = {
            "titleData": "提示",
            "bodyData": "确定要取消吗？"
        };
        $rootScope.confirmWindow(confirmParams, function () {
            updateStatus(info,'CANCEL');
        })
    }

     //延期
    $scope.delayedStatus=function(info){
        var confirmParams = {
            "titleData": "提示",
            "bodyData": "确定要延期吗？"
        };
        $rootScope.confirmWindow(confirmParams, function () {
            updateStatus(info,'DELAYED');
        })
    }


    //进展中
    $scope.ingStatus=function(info){
        var confirmParams = {
            "titleData": "提示",
            "bodyData": "确定要修改状态为进展中吗？"
        };
        $rootScope.confirmWindow(confirmParams, function () {
            updateStatus(info,'DOING');

        })
    }

    //完成
    $scope.completeStatus=function(info){
         var confirmParams = {
            "titleData": "提示",
            "bodyData": "确定要修改状态为已完成吗？"
        };
        $rootScope.confirmWindow(confirmParams, function () {
            updateStatus(info,'DONE');
        })
    }

    //更新方法
    $scope.update=function(info){
        $rootScope.taskSaveShow($scope.info.projectPlanId,info, null, function() {
            getPlanTaskList();
        });
    }

    //更新状态
    function updateStatus(info, type) {
        var postParams = info;
        postParams.status = type;
        var url = matrix_product_url +"/task/saveTask";
        $http({
            method   : "post",
            url      : url,
            data     : JSON.stringify(postParams),
            headers : {"Content-Type": "application/json"}
        }).success(function(result) {
            if(result.code == "0") {
                $rootScope.toasterSuccessInfo("更新成功！");
                getPlanTaskList();
            } else {
                $rootScope.toasterErrorInfo(result.desc);
            }
        });
    };

    //添加任务
    $scope.addTask=function(){
        $rootScope.taskSaveShow($scope.info.projectPlanId,null, null, function() {
            getPlanTaskList();
        });
    };


    //排序的compare方法
    /**
     *
     * @param prop 数组中对象的属性字段名
     * @returns {Function}
     */
    var compare =function(prop) {
        return function (a, b) {
            var dataA = a[prop]
            var dataB = b[prop]
            if (!isNaN(Number(dataA)) && !isNaN(Number(dataB))) {
                dataA = Number(dataA);
                dataB = Number(dataB);
            }
            if (dataA > dataB) {
                return -1; //表示放在前面
            } else if (dataA <dataB) {
                return 1;
            } else {
                return 0;
            }
        }
    }

}])